package edu.cuit.campus.portal.controller;

import com.alibaba.fastjson2.JSONObject;
import edu.cuit.campus.commons.response.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 1. form表单
 *      enctype="multipart/form-data" method="post"
 * 2. @MultipartConfig => servlet支持文件上传
 *      location: 临时文件路径
 *      maxFileSize: 单个文件的大小限制(字节)，-1表示没有限制(默认)
 *      maxRequestSize: 本次请求上传文件总大小限制(字节), -1表示没有限制(默认)
 *      fileSizeThreshold: 文件大小阈值,默认为0
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/9 9:04
 */
@WebServlet("/file/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        //获取上传的文件
        Part part = request.getPart("file");

        PrintWriter writer = response.getWriter();
        response.setContentType("application/json; charset=utf-8");
        if(part != null && part.getSize() > 0){
            System.out.println("field name:" + part.getName());
            String fileName = part.getSubmittedFileName();
            System.out.println("file name:" + fileName);
            String contentType = part.getContentType();
            System.out.println("文件类型:" + contentType);
            System.out.println("文件大小:" + part.getSize());

            //上传文件至文件服务器
           if(contentType.startsWith("image") || contentType.endsWith("pdf")){
               var type = contentType.startsWith("image") ? "images" : "resumes";
               part.write("D:/cuit/files/" + type + "/" + fileName); //上传
               writer.println(JSONObject.toJSONString(Result.ok("http://img.cuit.com/" + type + "/" + fileName)));
           }
        } else
            writer.println(JSONObject.toJSONString(Result.fail("文件非法")));

    }
}
